//
//  GMLookPDFVC.m
//  Teecloud
//
//  Created by 小熊 on 2018/12/7.
//  Copyright © 2018年 小志. All rights reserved.
//

#import "GMLookPDFVC.h"
#import "CGContextDrawPDFPageController.h"
@interface GMLookPDFVC ()
@property (nonatomic, assign) NSInteger totalPages;
@property (nonatomic, assign) NSInteger currentPag;
@end

@implementation GMLookPDFVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = kWhiteColor;
    self.title = @"文件预览";
    [self download];
}
-(void)download{
    NSString *downUrl = self.model.Url;
    NSArray *array = [self.model.Url componentsSeparatedByString:@"/"];
    NSString *fileName= [array lastObject];
    [MBProgressHUD showErrorOrSuc:@"处理中" toView:self.view];
    [HJNetwork downloadWithURL:downUrl fileDir:TENYUNDOWN fileName:fileName progress:^(NSProgress *progress) {
     
    } callback:^(NSString *path, NSError *error) {
        if (!error) {
           [self creatPDFwithPath:fileName];
        }else{
           [MBProgressHUD showErrorOrSuc:@"文件打开失败" toView:self.view];
        }
        
    }];
}
- (void)creatPDFwithPath:(NSString *)path{
    /* 根据pdf文件路径初始化pdf阅读视图 */
    //拼接缓存目录
    NSString *downloadDir = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject]stringByAppendingPathComponent:TENYUNDOWN];
    NSString *filePath = [NSString stringWithFormat:@"%@/%@",downloadDir,path];
    //创建CGPDFDocument对象
    CGPDFDocumentRef pdfDocument =  [self createPDFFromExistFile:filePath]; // 创建pdf文件对象
    pdfPageModel = [[CGContextDrawPDFPageModel alloc] initWithPDFDocument:pdfDocument];
    kWeakObject(self)
    pdfPageModel.pageBlock = ^(NSInteger curentPag) {
        weakself.currentPag =curentPag;
        NSLog(@"%ld",curentPag);
    };
    
    // UIPageViewControllerSpineLocationMin 单页显示
    NSDictionary *options = [NSDictionary dictionaryWithObject:
                             [NSNumber numberWithInteger: UIPageViewControllerSpineLocationMin]
                                                        forKey: UIPageViewControllerOptionSpineLocationKey];
    //初始化UIPageViewController，UIPageViewControllerTransitionStylePageCurl翻页效果，UIPageViewControllerNavigationOrientationHorizontal水平方向翻页
    pageViewCtrl = [[UIPageViewController alloc] initWithTransitionStyle:UIPageViewControllerTransitionStylePageCurl
                                                   navigationOrientation:UIPageViewControllerNavigationOrientationHorizontal
                                                                 options:options];
    //承载pdf每页内容的控制器
    CGContextDrawPDFPageController *initialViewController = [pdfPageModel viewControllerAtIndex:1];
    NSArray *viewControllers = [NSArray arrayWithObject:initialViewController];
    //设置UIPageViewController的数据源
    [pageViewCtrl setDataSource:pdfPageModel];
    //设置正反面都有文字
    pageViewCtrl.doubleSided = YES;
    pageViewCtrl.view.frame = CGRectMake(0, 0, self.view.frame.size.width,self.view.frame.size.height);
    //设置pageViewCtrl的子控制器
    [pageViewCtrl setViewControllers:viewControllers
                           direction:UIPageViewControllerNavigationDirectionReverse
                            animated:NO
                          completion:^(BOOL f){}];
    [self addChildViewController:pageViewCtrl];
    [self.view addSubview:pageViewCtrl.view];
    //当我们向我们的视图控制器容器（就是父视图控制器，它调用addChildViewController方法加入子视图控制器，它就成为了视图控制器的容器）中添加（或者删除）子视图控制器后，必须调用该方法，告诉iOS，已经完成添加（或删除）子控制器的操作。
    [pageViewCtrl didMoveToParentViewController:self];

}
/* 根据文件路径创建pdf文件 */
- (CGPDFDocumentRef)createPDFFromExistFile:(NSString *)aFilePath {
    CFStringRef path;
    CFURLRef url;
    CGPDFDocumentRef document;
    
    path = CFStringCreateWithCString(NULL, [aFilePath UTF8String], kCFStringEncodingUTF8);
    url =  CFURLCreateWithFileSystemPath(NULL, path, kCFURLPOSIXPathStyle, NO);
    CFRelease(path);
    
    document = CGPDFDocumentCreateWithURL(url);
    CFRelease(url);
    self.totalPages = CGPDFDocumentGetNumberOfPages(document); // 设置PDF文件总页数
    if (self.totalPages == 0) { // 创建出错处理
        NSLog(@"Create Error");
        return NULL;
    }
    return document;
}

@end
